# coding=utf-8
import logging
from c21_qrcode.common.sce_redis import SceRedis
import json

logger = logging.getLogger('error')


class SLurl(object):

    def __init__(self):
        self.myredis = SceRedis.instance()
        self.redis_master = self.myredis.redis_master
        self.redis_slave = self.myredis.redis_slave

    def set(self, key, value, ex=None):
        value = json.dumps(value)
        self.redis_master.set(key, value, ex=ex)

    def set_only_key(self, key, value, ex=None):
        original_value = self.redis_slave.get(key)
        if not original_value:
            self.set(key, value, ex=ex)
            return True
        original_value = json.loads(original_value)
        if original_value['long_url'] == value['long_url']:
            self.set(key, value, ex=ex)
            return True

        error_info = 'err:ShortUrl Repeat,short_url:{0},long_url:{1}'.format(
            key, value['long_url'])
        logger.error(error_info)
        return False

    def get(self, key):
        value = self.redis_slave.get(key)
        if not value:
            return value
        return json.loads(value)


class ScanCensus(object):
    '''
        统计二维码扫描数
    '''

    def __init__(self):
        self.myredis = SceRedis.instance()
        self.redis_master = self.myredis.redis_master
        self.redis_slave = self.myredis.redis_slave

    def add_scan_num(self, short_url):
        key = '{0}_ScanNum'.format(short_url)
        self.redis_master.incr(key)

    def get_scan_num(self, short_url):
        key = '{0}_ScanNum'.format(short_url)
        res = self.redis_slave.get(key)
        res = int(res) if res else 0
        return res

    def mget_scan_num(self, short_urls):
        tmp = []
        if not short_urls:
            return []
        for i in range(len(short_urls)):
            tmp.append('{0}_ScanNum'.format(short_urls[i]))
        res = self.redis_slave.mget(tmp)
        return res


if __name__ == "__main__":
    pass
